#include <iostream>
#include <pthread.h>
#include <unistd.h>


pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;//mutex和cond定义为全局变量或静态变量，不需要调用mutex、cond对应的初始化、销毁函数
#define NUM 3
int cnt = 0;
void* Count(void* arg)
{
    pthread_detach(pthread_self());//分离线程 系统将来会自动释放该线程，不用我们调用函数释放
    unsigned int num = (unsigned int)arg;
    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);
        std::cout<<"thread "<<num <<" ,cnt: "<<cnt++<<std::endl;
        pthread_mutex_unlock(&mutex);
    }
}
int main()
{
    // uint64_t v=2;
    // unsigned long int g=3;


    for(int i = 1;i<=NUM;i++)
    {
        pthread_t tid;
        pthread_create(&tid,nullptr,Count,(void*)i);
    }

    for(int i=1;i<=NUM;i++)//由主线程唤醒在条件变量中等待阻塞的线程
    {
        sleep(1);
        pthread_cond_signal(&cond);
    }
    return 0;
}